package com.medical.app.controller;

import com.medical.app.dto.request.MedicationRequest;
import com.medical.app.dto.response.ApiResponse;
import com.medical.app.entity.Medication;
import com.medical.app.entity.User;
import com.medical.app.service.MedicationService;
import com.medical.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/medications")
@CrossOrigin(origins = "*")
public class MedicationController {

    @Autowired
    private MedicationService medicationService;

    @Autowired
    private UserService userService;

    @GetMapping("/user/{userId}")
    public ResponseEntity<ApiResponse<List<Medication>>> getUserMedications(@PathVariable Long userId) {
        try {
            if (!userService.findById(userId).isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }
            List<Medication> medications = medicationService.getUserMedications(userId);
            return ResponseEntity.ok(ApiResponse.success(medications));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Medication>> createMedication(@RequestBody MedicationRequest request) {
        try {
            Optional<User> user = userService.findById(request.getUserId());
            if (!user.isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            Medication medication = new Medication();
            medication.setName(request.getName());
            medication.setDosage(request.getDosage());
            medication.setFrequency(request.getFrequency());
            medication.setStartDate(request.getStartDate());
            medication.setEndDate(request.getEndDate());
            medication.setNotes(request.getNotes());
            medication.setReminder(request.getReminder());
            medication.setImageUrls(request.getImageUrls());
            medication.setUser(user.get());

            Medication savedMedication = medicationService.saveMedication(medication);
            return ResponseEntity.ok(ApiResponse.success("创建成功", savedMedication));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<String>> deleteMedication(@PathVariable Long id) {
        try {
            medicationService.deleteMedication(id);
            return ResponseEntity.ok(ApiResponse.success("删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 在MedicationController中添加以下方法：

    // 更新药品记录
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Medication>> updateMedication(
            @PathVariable Long id,
            @RequestBody MedicationRequest request) {
        try {
            Optional<Medication> existingMedication = medicationService.findById(id);
            if (!existingMedication.isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("药品记录不存在"));
            }

            // 验证用户权限
            Medication medication = existingMedication.get();
            if (!medication.getUser().getId().equals(request.getUserId())) {
                return ResponseEntity.badRequest().body(ApiResponse.error("无权修改此记录"));
            }

            // 创建更新对象
            Medication medicationToUpdate = new Medication();
            medicationToUpdate.setName(request.getName());
            medicationToUpdate.setDosage(request.getDosage());
            medicationToUpdate.setFrequency(request.getFrequency());
            medicationToUpdate.setStartDate(request.getStartDate());
            medicationToUpdate.setEndDate(request.getEndDate());
            medicationToUpdate.setNotes(request.getNotes());
            medicationToUpdate.setReminder(request.getReminder());
            medicationToUpdate.setImageUrls(request.getImageUrls());

            Medication updatedMedication = medicationService.updateMedication(id, medicationToUpdate);
            return ResponseEntity.ok(ApiResponse.success("更新成功", updatedMedication));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 获取单个药品记录详情
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Medication>> getMedicationById(@PathVariable Long id) {
        try {
            Optional<Medication> medication = medicationService.findById(id);
            if (medication.isPresent()) {
                return ResponseEntity.ok(ApiResponse.success(medication.get()));
            } else {
                return ResponseEntity.badRequest().body(ApiResponse.error("药品记录不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
}